package org.crc.myvhrb.controller;

import org.crc.myvhrb.model.ChatMsg;
import org.crc.myvhrb.model.Hr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * CRC
 * 2021/8/20
 */
@RestController
public class WsController {

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/ws/chat")
    public void handleMsg(Authentication authentication, ChatMsg chatMsg){
        Hr hr = ((Hr) authentication.getPrincipal());
        // 发送的用户账号
        chatMsg.setFrom(hr.getUsername());
        // 发送的用户名称
        chatMsg.setFromNickname(hr.getName());
        chatMsg.setDate(new Date());
        // 参数1：消息发送目标， 参数2： 消息队列，参数3： 消息内容
        simpMessagingTemplate.convertAndSendToUser(chatMsg.getTo(),"/queue/chat",chatMsg);
    }

}
